package com.tfswx.jcyw.dmzc.window;

import com.intellij.openapi.ui.DialogWrapper;
import com.intellij.ui.JBColor;
import com.tfswx.jcyw.dmzc.config.CommonData;
import com.tfswx.jcyw.dmzc.enums.Lx;

import javax.imageio.ImageIO;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;

/**
 * @author ricky
 * @date 2022/12/30
 */
public class Tp extends DialogWrapper {
    private JPanel windowPanel;

    private final ButtonGroup buttonGroup;
    private JRadioButton doodleRadioButton;
    private JRadioButton lineRadioButton;
    private JRadioButton circleRadioButton;
    private JRadioButton rectRadioButton;
    private JSlider cxSlider;
    private JLabel tpLabel;
    private JLabel cxSliderVal;
    private JScrollPane tpScrollPane;
    private JPanel colorPanel;

    //记录鼠标坐标
    private int x = 0;
    private int y = 0;

    private BufferedImage bi;
    private Graphics2D g2d;

    private ImageIcon tp;

    public Tp(byte[] imageBytes) {
        super(false);
        setTitle("图片编辑");
        buttonGroup = new ButtonGroup();
        buttonGroup.add(doodleRadioButton);
        buttonGroup.add(lineRadioButton);
        buttonGroup.add(circleRadioButton);
        buttonGroup.add(rectRadioButton);
        CommonData.imageByte = imageBytes;
        tp = new ImageIcon(imageBytes);
        tpLabel.setIcon(tp);

        tpScrollPane.getHorizontalScrollBar().setUnitIncrement(16);
        tpScrollPane.getVerticalScrollBar().setUnitIncrement(16);
        tpScrollPane.setBorder(BorderFactory.createEmptyBorder());

        cxSlider.addChangeListener(changeEvent -> {
            JSlider source = (JSlider) changeEvent.getSource();
            cxSliderVal.setText(source.getValue() / 10F + "");
        });

//        colorButton.setBorder(BorderFactory.createEmptyBorder());
//        colorButton.setOpaque(true);
        colorPanel.setBackground(JBColor.RED);
//        colorButton.setForeground(Color.RED);

        colorPanel.setPreferredSize(new Dimension(20, 20));
//        colorButton.setContentAreaFilled(false);
//        colorButton.setBorderPainted(false);
        addEventListener();
        init();
    }

    private void addEventListener() {
        colorPanel.addMouseListener(new MouseAdapter() {
            @Override
            public void mouseClicked(MouseEvent e) {
                Color selectedColor = JColorChooser.showDialog(windowPanel, "选择颜色", colorPanel.getBackground());
                if (selectedColor != null) {
                    colorPanel.setBackground(selectedColor);
                }
            }
        });
        tpLabel.addMouseWheelListener(mouseWheelEvent -> {
            int wheelRotation = mouseWheelEvent.getWheelRotation();
            int tickSpacing = cxSlider.getMajorTickSpacing();
            if (wheelRotation < 0) {
                cxSlider.setValue(cxSlider.getValue() + tickSpacing);
            } else if (wheelRotation > 0) {
                cxSlider.setValue(cxSlider.getValue() - tickSpacing);
            }
        });
        tpLabel.addMouseListener(new MouseAdapter() {

            @Override
            public void mousePressed(MouseEvent e) {
                x = getX(e.getX());
                y = e.getY();

                tp = (ImageIcon) tpLabel.getIcon();
            }

            @Override
            public void mouseReleased(MouseEvent e) {
                if (g2d != null) {
                    g2d.dispose();
                    g2d = null;
                }
            }
        });
        tpLabel.addMouseMotionListener(new MouseAdapter() {
            @Override
            public void mouseDragged(MouseEvent e) {
                int xEnd = getX(e.getX());
                int yEnd = e.getY();
                //1. 取得imageLabel中的图像
                Image img = tp.getImage();
                //2. 创建一个缓冲图形对象 bi
                bi = new BufferedImage(img.getWidth(null), img.getHeight(null), BufferedImage.TYPE_INT_RGB);
                g2d = getG2d(img, bi);

                switch (getSelected()) {
                    case doodle: {
                        g2d.drawLine(x, y, xEnd, yEnd); //Java中没有提供点的绘制，使用起点和终点为同一个点的画线代替
                        tpLabel.setIcon(tp = new ImageIcon(bi));

                        g2d.dispose();
                        g2d = null;
                        //下次画线起点是设置为这次画线的终点
                        x = xEnd;
                        y = yEnd;
                        break;
                    }
                    case line: {
                        g2d.drawLine(x, y, xEnd, yEnd); //Java中没有提供点的绘制，使用起点和终点为同一个点的画线代替
                        tpLabel.setIcon(new ImageIcon(bi));
                        break;
                    }
                    case circle: {
                        g2d.drawOval(Math.min(x, xEnd), Math.min(y, yEnd), Math.abs(xEnd - x), Math.abs(yEnd - y));
                        tpLabel.setIcon(new ImageIcon(bi));
                        break;
                    }
                    case rect: {
                        g2d.drawRect(Math.min(x, xEnd), Math.min(y, yEnd), Math.abs(xEnd - x), Math.abs(yEnd - y));
                        tpLabel.setIcon(new ImageIcon(bi));
                        break;
                    }
                    default:
                }
            }
        });
    }

    int getX(int x) {
        int rootWidth = tpLabel.getRootPane().getWidth();
        int width = tpLabel.getWidth();
        return x - (rootWidth - width) / 2;
    }

    private Graphics2D getG2d(Image img, BufferedImage bi) {
        Graphics2D g2d = (Graphics2D) bi.getGraphics();
        g2d.drawImage(img, 0, 0, null);
        g2d.setColor(colorPanel.getBackground());
        g2d.setStroke(new BasicStroke(cxSlider.getValue() / 10F));
        return g2d;
    }

    private Lx getSelected() {
        ButtonModel selection = buttonGroup.getSelection();
        if (selection == doodleRadioButton.getModel()) {
            return Lx.doodle;
        } else if (selection == lineRadioButton.getModel()) {
            return Lx.line;
        } else if (selection == circleRadioButton.getModel()) {
            return Lx.circle;
        } else if (selection == rectRadioButton.getModel()) {
            return Lx.rect;
        } else {
            System.out.println("不支持");
            throw new RuntimeException("暂不支持的类型");
        }
    }

    @Override
    protected JComponent createCenterPanel() {
        return windowPanel;
    }

    @Override
    protected Action[] createActions() {
        return new Action[]{new AbstractAction("完成编辑") {
            @Override
            public void actionPerformed(ActionEvent actionEvent) {
                ImageIcon icon = (ImageIcon) tpLabel.getIcon();
                Image image = icon.getImage();
                if (image instanceof BufferedImage) {
                    BufferedImage img = (BufferedImage) image;
                    try (ByteArrayOutputStream bos = new ByteArrayOutputStream()) {
                        ImageIO.write(img, "jpg", bos);
                        CommonData.imageByte = bos.toByteArray();
                    } catch (IOException e) {
                        throw new RuntimeException(e);
                    }
                }
                close(OK_EXIT_CODE);
            }
        }};
    }


}